import copy

from django.conf import settings

class ModuleCache(object):
    def __init__(self):
        self.default_modules = []
        self.discovered = False
        self.modules = {}

    def register(self, name, module):
        """
        Register the module in cache for later use.
        """
        if name in self.modules:
            raise KeyError, "Only one module named %s can be registered." % name
        self.modules[name] = module
    
        if module.is_default:
            # Add to a special cache for default modules
            self.default_modules.append(module)

    def discover_modules(self):
        if self.discovered:
            return
        for app in settings.INSTALLED_APPS:
            # Just loading the module will do the trick
            __import__(app, {}, {}, ['modules'])
        self.discovered = True

    def get_all_modules(self):
        print "Getting all modules"
        self.discover_modules()
        return self.modules.values()

    def get_module(self, name):
        """
        Retrieve a module from the cache.
        """
        self.discover_modules()
        return self.modules[name]

    def get_defaults(self):
        """
        Get a list of default moduels.
        """
        self.discover_modules()
        return set(self.default_modules)

registry = ModuleCache()
